const mongoose = require('mongoose');
const Order = require('../models/order.model');
const Product = require('../models/product.model');
const { AppError } = require('../middlewares/error.middleware');

/**
 * 创建新订单
 * POST /api/orders
 */
exports.createOrder = async (req, res, next) => {
  try {
    const {
      orderItems,
      shippingAddress,
      paymentMethod,
      itemsPrice,
      shippingPrice,
      taxPrice,
      totalPrice
    } = req.body;

    // 验证购物车不为空
    if (!orderItems || orderItems.length === 0) {
      throw new AppError('购物车为空', 400);
    }

    // 验证商品库存
    for (const item of orderItems) {
      const product = await Product.findById(item.product);
      if (!product) {
        throw new AppError(`商品不存在: ${item.name}`, 404);
      }
      if (product.countInStock < item.qty) {
        throw new AppError(`${product.name} 库存不足`, 400);
      }
    }

    // 创建新订单
    const order = new Order({
      orderNo: Order.generateOrderNo(),
      user: req.user._id,
      orderItems,
      shippingAddress,
      paymentMethod,
      itemsPrice,
      shippingPrice,
      taxPrice,
      totalPrice,
    });

    // 保存订单
    const createdOrder = await order.save();

    // 更新商品库存
    for (const item of orderItems) {
      const product = await Product.findById(item.product);
      product.countInStock -= item.qty;
      product.salesCount += item.qty;
      await product.save();
    }

    res.status(201).json(createdOrder);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取当前用户的所有订单
 * GET /api/orders
 */
exports.getMyOrders = async (req, res, next) => {
  try {
    const { status, page = 1, limit = 10 } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);

    // 构建查询条件
    const query = { user: req.user._id };
    if (status && status !== 'all') {
      query.orderStatus = status;
    }

    // 查询订单
    const orders = await Order.find(query)
      .populate('orderItems.product', 'name mainImage price')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    // 计算总数
    const total = await Order.countDocuments(query);

    res.json({
      orders,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        pages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取订单详情
 * GET /api/orders/:id
 */
exports.getOrderById = async (req, res, next) => {
  try {
    const order = await Order.findById(req.params.id)
      .populate('user', 'name email')
      .populate('orderItems.product', 'name mainImage price brand category');

    // 验证订单是否存在
    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    // 验证用户是否有权限查看此订单（只能查看自己的订单）
    if (order.user._id.toString() !== req.user._id.toString()) {
      throw new AppError('没有权限查看此订单', 403);
    }

    // 格式化订单数据，确保字段名与前端期望一致
    const formattedOrder = {
      id: order._id,
      orderNumber: order.orderNo,
      userId: order.user._id,
      orderItems: order.orderItems.map(item => ({
        id: item._id,
        productId: item.product ? item.product._id : item.product,
        name: item.name,
        image: item.image,
        price: item.price,
        quantity: item.qty,
        color: item.specifications?.get('颜色') || item.specifications?.get('color'),
        size: item.specifications?.get('尺寸') || item.specifications?.get('size'),
        specifications: item.specifications ? Object.fromEntries(item.specifications) : {}
      })),
      shippingAddress: order.shippingAddress,
      paymentMethod: order.paymentMethod,
      paymentResult: order.paymentResult,
      itemsPrice: order.itemsPrice,
      shippingPrice: order.shippingPrice,
      taxPrice: order.taxPrice,
      discountPrice: order.discountPrice || 0,
      totalPrice: order.totalPrice,
      isPaid: order.isPaid,
      paidAt: order.paidAt,
      isDelivered: order.isDelivered,
      deliveredAt: order.deliveredAt,
      trackingNumber: order.trackingNumber,
      status: order.orderStatus,
      note: order.note,
      couponCode: order.couponCode,
      refundInfo: order.refundInfo,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt
    };

    res.json(formattedOrder);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取订单详情 (管理员)
 * GET /api/admin/orders/:id
 */
exports.getOrderByIdAdmin = async (req, res, next) => {
  try {
    const orderId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(orderId)) {
      return res.status(400).json({
        success: false,
        message: '无效的订单ID'
      });
    }

    const order = await Order.findById(orderId)
      .populate('user', 'name email avatar phone')
      .populate('orderItems.product', 'name mainImage price brand category');

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 格式化订单数据
    const formattedOrder = {
      _id: order._id,
      orderNo: order.orderNo,
      userId: order.user._id,
      userName: order.user.name,
      userEmail: order.user.email,
      userAvatar: order.user.avatar,
      userPhone: order.user.phone,
      orderItems: order.orderItems.map(item => ({
        id: item._id,
        productId: item.product._id,
        name: item.product.name,
        image: item.product.mainImage,
        price: item.price,
        quantity: item.qty,
        specifications: item.specifications
      })),
      totalPrice: order.totalPrice,
      orderStatus: order.orderStatus,
      isPaid: order.isPaid,
      paymentMethod: order.paymentMethod || '未选择',
      paymentResult: order.paymentResult,
      isDelivered: order.isDelivered,
      deliveredAt: order.deliveredAt,
      shippingAddress: order.shippingAddress,
      refundInfo: order.refundInfo,
      remark: order.remark,
      trackingNumber: order.trackingNumber,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt,
      paidAt: order.paidAt
    };

    res.json({
      success: true,
      data: formattedOrder
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    next(error);
  }
};

/**
 * 更新订单为已支付状态
 * PUT /api/orders/:id/pay
 */
exports.updateOrderToPaid = async (req, res, next) => {
  try {
    const { paymentResult } = req.body;

    const order = await Order.findById(req.params.id);

    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    // 验证用户是否有权限更新此订单（只能更新自己的订单）
    if (order.user.toString() !== req.user._id.toString()) {
      throw new AppError('没有权限更新此订单', 403);
    }

    // 更新订单状态
    order.isPaid = true;
    order.paidAt = Date.now();
    order.paymentResult = paymentResult;

    const updatedOrder = await order.save();

    res.json(updatedOrder);
  } catch (error) {
    next(error);
  }
};

/**
 * 更新订单为已发货状态（管理员）
 * PUT /api/orders/:id/deliver
 */
exports.updateOrderToDelivered = async (req, res, next) => {
  try {
    const order = await Order.findById(req.params.id);

    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    // 更新订单状态
    order.isDelivered = true;
    order.deliveredAt = Date.now();

    const updatedOrder = await order.save();

    res.json(updatedOrder);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取所有订单（管理员）
 * GET /api/admin/orders
 */
exports.getOrders = async (req, res, next) => {
  try {
    // 分页参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;

    // 构建查询条件
    const query = {};

    // 状态筛选
    if (req.query.status && req.query.status !== '') {
      query.orderStatus = req.query.status;
    }

    // 支付状态筛选
    if (req.query.paymentStatus && req.query.paymentStatus !== '') {
      query.isPaid = req.query.paymentStatus === 'paid';
    }

    // 关键词搜索（订单号或用户名）
    if (req.query.keyword && req.query.keyword.trim() !== '') {
      const keyword = req.query.keyword.trim();
      // 如果是订单号格式，直接搜索订单号
      if (keyword.startsWith('ORD')) {
        query.orderNo = { $regex: keyword, $options: 'i' };
      } else {
        // 否则搜索用户信息，需要先查找用户
        const User = require('../models/User');
        const users = await User.find({
          $or: [
            { name: { $regex: keyword, $options: 'i' } },
            { email: { $regex: keyword, $options: 'i' } }
          ]
        }).select('_id');

        if (users.length > 0) {
          query.user = { $in: users.map(u => u._id) };
        } else {
          // 如果没找到用户，也尝试搜索订单号
          query.orderNo = { $regex: keyword, $options: 'i' };
        }
      }
    }

    // 查询订单
    const orders = await Order.find(query)
      .populate('user', 'name email avatar')
      .populate('orderItems.product', 'name mainImage price')
      .skip(skip)
      .limit(limit)
      .sort({ createdAt: -1 });

    // 计算总订单数
    const totalOrders = await Order.countDocuments(query);

    // 格式化订单数据以匹配前端期望的格式
    const formattedOrders = orders.map(order => ({
      id: order._id,
      orderNo: order.orderNo,
      userId: order.user._id,
      userName: order.user.name,
      userEmail: order.user.email,
      userAvatar: order.user.avatar,
      orderItems: order.orderItems.map(item => {
        // 处理图片URL，确保它是完整的URL
        let imageUrl = item.product.mainImage;
        if (imageUrl && !imageUrl.startsWith('http')) {
          // 如果是相对路径，转换为完整URL
          const baseUrl = `${req.protocol}://${req.get('host')}`;
          imageUrl = imageUrl.startsWith('/') ? `${baseUrl}${imageUrl}` : `${baseUrl}/${imageUrl}`;
        }

        return {
          id: item._id,
          productId: item.product._id,
          name: item.product.name,
          image: imageUrl,
          price: item.price,
          quantity: item.qty,
          specifications: item.selectedSpecs
        };
      }),
      totalPrice: order.totalPrice,
      orderStatus: order.orderStatus,
      isPaid: order.isPaid,
      paymentMethod: order.paymentMethod || '未选择',
      paymentResult: order.paymentResult,
      isDelivered: order.isDelivered,
      deliveredAt: order.deliveredAt,
      shippingAddress: order.shippingAddress,
      refundInfo: order.refundInfo,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt
    }));

    res.json({
      data: formattedOrders,
      total: totalOrders,
      page,
      limit,
      pages: Math.ceil(totalOrders / limit)
    });
  } catch (error) {
    console.error('获取订单列表错误:', error);
    next(error);
  }
};

/**
 * 取消订单
 * PUT /api/orders/:id/cancel
 */
exports.cancelOrder = async (req, res, next) => {
  try {
    const order = await Order.findById(req.params.id);

    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    // 验证用户是否有权限取消此订单
    if (order.user.toString() !== req.user._id.toString()) {
      throw new AppError('没有权限取消此订单', 403);
    }

    // 只有待付款和待发货的订单可以取消
    if (!['待付款', '待发货'].includes(order.orderStatus)) {
      throw new AppError('该订单状态不允许取消', 400);
    }

    // 更新订单状态
    order.orderStatus = '已取消';

    // 如果订单已支付，需要退款
    if (order.isPaid) {
      order.orderStatus = '已退款';
    }

    // 恢复商品库存
    for (const item of order.orderItems) {
      const product = await Product.findById(item.product);
      if (product) {
        product.countInStock += item.qty;
        product.salesCount = Math.max(0, product.salesCount - item.qty);
        await product.save();
      }
    }

    const updatedOrder = await order.save();

    res.json({
      message: '订单已取消',
      order: updatedOrder
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 申请退款
 * POST /api/orders/:id/refund
 */
exports.requestRefund = async (req, res, next) => {
  try {
    const { reason, description } = req.body;
    const order = await Order.findById(req.params.id);

    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    // 验证用户是否有权限申请退款
    if (order.user.toString() !== req.user._id.toString()) {
      throw new AppError('没有权限申请退款', 403);
    }

    // 检查订单状态是否允许退款
    if (!['待发货', '已发货'].includes(order.orderStatus)) {
      throw new AppError('该订单状态不允许申请退款', 400);
    }

    // 对于"待发货"和"已发货"状态的订单，我们认为是可以申请退款的
    // 因为这些状态通常意味着订单已经支付或者至少已经确认
    if (order.orderStatus === '待付款') {
      throw new AppError('待付款订单无法申请退款，请先取消订单', 400);
    }

    // 检查是否已经申请过退款
    if (order.orderStatus === '已退款') {
      throw new AppError('订单已退款', 400);
    }

    // 更新订单状态为申请退款中（可以添加一个新的状态）
    order.orderStatus = '退款中';
    order.refundInfo = {
      reason,
      description,
      requestedAt: new Date(),
      status: 'pending'
    };

    const updatedOrder = await order.save();

    res.json({
      message: '退款申请已提交，请等待处理',
      order: updatedOrder
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新订单状态
 * PUT /api/orders/:id/status
 */
exports.updateOrderStatus = async (req, res, next) => {
  try {
    const { status, trackingNumber } = req.body;
    const order = await Order.findById(req.params.id);

    if (!order) {
      throw new AppError('订单不存在', 404);
    }

    // 权限验证：用户只能更新自己的订单，管理员可以更新所有订单
    const isOwner = order.user.toString() === req.user._id.toString();
    const isAdmin = req.user.role && ['admin', 'seller', 'customer_service'].includes(req.user.role);

    if (!isOwner && !isAdmin) {
      throw new AppError('没有权限更新此订单', 403);
    }

    // 验证状态值
    const validStatuses = ['待付款', '待发货', '已发货', '已完成', '已取消', '已退款'];
    if (!validStatuses.includes(status)) {
      throw new AppError('无效的订单状态', 400);
    }

    // 状态转换验证：确保状态转换的合理性
    const currentStatus = order.orderStatus;
    const invalidTransitions = {
      '已完成': ['待付款', '待发货', '已发货'],
      '已取消': ['待发货', '已发货', '已完成'],
      '已退款': ['待付款', '待发货', '已发货']
    };

    if (invalidTransitions[currentStatus] && invalidTransitions[currentStatus].includes(status)) {
      throw new AppError(`订单状态不能从"${currentStatus}"变更为"${status}"`, 400);
    }

    // 更新订单状态
    order.orderStatus = status;

    // 如果状态变为"待发货"，说明已支付，更新支付状态
    if (status === '待发货' && !order.isPaid) {
      order.isPaid = true;
      order.paidAt = new Date();
    }

    // 如果是发货状态，更新发货信息
    if (status === '已发货') {
      order.isDelivered = true;
      order.deliveredAt = Date.now();
      if (trackingNumber) {
        order.trackingNumber = trackingNumber;
      }
    }

    // 如果是完成状态，确保已发货
    if (status === '已完成') {
      order.isDelivered = true;
      if (!order.deliveredAt) {
        order.deliveredAt = Date.now();
      }
    }

    const updatedOrder = await order.save();

    res.json({
      message: '订单状态已更新',
      order: updatedOrder
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取订单统计信息
 * GET /api/orders/stats
 */
exports.getOrderStats = async (req, res, next) => {
  try {
    const userId = req.user._id;

    // 获取用户订单统计
    const stats = await Order.aggregate([
      { $match: { user: userId } },
      {
        $group: {
          _id: '$orderStatus',
          count: { $sum: 1 },
          totalAmount: { $sum: '$totalPrice' }
        }
      }
    ]);

    // 格式化统计结果
    const formattedStats = {
      待付款: { count: 0, totalAmount: 0 },
      待发货: { count: 0, totalAmount: 0 },
      已发货: { count: 0, totalAmount: 0 },
      已完成: { count: 0, totalAmount: 0 },
      已取消: { count: 0, totalAmount: 0 },
      已退款: { count: 0, totalAmount: 0 }
    };

    stats.forEach(stat => {
      if (formattedStats[stat._id]) {
        formattedStats[stat._id] = {
          count: stat.count,
          totalAmount: stat.totalAmount
        };
      }
    });

    // 计算总计
    const totalOrders = stats.reduce((sum, stat) => sum + stat.count, 0);
    const totalAmount = stats.reduce((sum, stat) => sum + stat.totalAmount, 0);

    res.json({
      stats: formattedStats,
      summary: {
        totalOrders,
        totalAmount
      }
    });
  } catch (error) {
    next(error);
  }
};

